<template>
  <div class="evaluation-list">
    <div class="evaluation-header">
      <h3>商品评价 ({{ total }})</h3>
      <div class="rating-overview">
        <div class="average-rating">
          <span class="score">{{ averageRating.toFixed(1) }}</span>
          <div class="stars">
            <el-rate v-model="averageRating" disabled show-score :score-template="{value}" />
          </div>
        </div>
        <div class="rating-distribution">
          <div v-for="i in 5" :key="i" class="rating-bar">
            <span class="star-count">{{ i }}星</span>
            <el-progress 
              :percentage="ratingDistribution[i] || 0" 
              :show-text="false" 
              :stroke-width="8"
            />
            <span class="count">{{ ratingCounts[i] || 0 }}</span>
          </div>
        </div>
      </div>
    </div>
    
    <div v-if="loading" class="loading">
      <el-skeleton :rows="3" animated />
    </div>
    
    <div v-else-if="evaluations.length === 0" class="empty">
      <el-empty description="暂无评价" />
    </div>
    
    <div v-else class="evaluations">
      <div v-for="evaluation in evaluations" :key="evaluation.eva_id" class="evaluation-item">
        <div class="user-info">
          <img :src="evaluation.avatarImg || '/default-avatar.png'" alt="用户头像" class="avatar" />
          <div class="user-details">
            <span class="username">{{ evaluation.userName || '匿名用户' }}</span>
            <div class="rating">
              <el-rate v-model="evaluation.stars" disabled size="small" />
              <span class="date">{{ formatDate(evaluation.send_date) }}</span>
            </div>
          </div>
        </div>
        <div class="content">
          {{ evaluation.evaluation }}
        </div>
        <div class="actions">
          <el-button type="text" size="small" @click="handleLike(evaluation.eva_id)">
            <el-icon><Star /></el-icon>
            {{ evaluation.likes || 0 }}
          </el-button>
        </div>
      </div>
    </div>
    
    <div v-if="total > pageSize" class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 20, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { getGoodsEvaluationAPI } from '@/apis/goods'

const props = defineProps({
  gid: {
    type: [String, Number],
    required: true
  }
})

const evaluations = ref([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

const averageRating = computed(() => {
  if (evaluations.value.length === 0) return 0
  const sum = evaluations.value.reduce((acc, item) => acc + item.stars, 0)
  return sum / evaluations.value.length
})

const ratingCounts = computed(() => {
  const counts = {}
  for (let i = 1; i <= 5; i++) {
    counts[i] = evaluations.value.filter(e => e.stars === i).length
  }
  return counts
})

const ratingDistribution = computed(() => {
  const distribution = {}
  for (let i = 1; i <= 5; i++) {
    distribution[i] = total.value > 0 ? (ratingCounts.value[i] / total.value) * 100 : 0
  }
  return distribution
})

const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

const loadEvaluations = async () => {
  loading.value = true
  try {
    const res = await getGoodsEvaluationAPI(props.gid)
    if (res.code === 200) {
      evaluations.value = res.data || []
      total.value = evaluations.value.length
    }
  } catch (error) {
    console.error('获取评价失败:', error)
    ElMessage.error('获取评价失败')
  } finally {
    loading.value = false
  }
}

const handleLike = (evaId) => {
  // 点赞功能待实现
  ElMessage.info('点赞功能开发中')
}

const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  currentPage.value = 1
  loadEvaluations()
}

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
  loadEvaluations()
}

watch(() => props.gid, (newGid) => {
  if (newGid) {
    loadEvaluations()
  }
})

onMounted(() => {
  if (props.gid) {
    loadEvaluations()
  }
})
</script>

<style scoped>
.evaluation-list {
  margin-top: 24px;
}

.evaluation-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.evaluation-header h3 {
  margin: 0;
  color: #303133;
}

.rating-overview {
  display: flex;
  gap: 32px;
  align-items: center;
}

.average-rating {
  text-align: center;
}

.score {
  display: block;
  font-size: 24px;
  font-weight: bold;
  color: #ff5000;
}

.rating-distribution {
  flex: 1;
}

.rating-bar {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.star-count {
  width: 40px;
  font-size: 12px;
  color: #606266;
}

.rating-bar .el-progress {
  flex: 1;
}

.count {
  width: 30px;
  font-size: 12px;
  color: #909399;
  text-align: right;
}

.evaluation-item {
  padding: 16px;
  border-bottom: 1px solid #ebeef5;
}

.evaluation-item:last-child {
  border-bottom: none;
}

.user-info {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  margin-right: 12px;
}

.user-details {
  flex: 1;
}

.username {
  font-weight: 500;
  color: #303133;
}

.rating {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-top: 4px;
}

.date {
  font-size: 12px;
  color: #909399;
}

.content {
  color: #606266;
  line-height: 1.6;
  margin-bottom: 12px;
}

.actions {
  text-align: right;
}

.pagination {
  margin-top: 24px;
  text-align: center;
}

.loading {
  padding: 20px;
}

.empty {
  padding: 40px 0;
}
</style>